package com.fanjia.taobao.user.controller;

import com.fanjia.taobao.common.util.*;
import com.fanjia.taobao.common.util.sms.SmsServiceUtil;
import com.fanjia.taobao.user.entity.Sms;
import com.fanjia.taobao.user.entity.User;

import com.fanjia.taobao.user.service.UserService;
import com.github.qcloudsms.httpclient.HTTPException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息表(User)表控制层
 *
 * @author fanjia
 * @since 2021-04-07 17:08:20
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    SmsServiceUtil smsService;
    @Autowired
    AuthenticationManagerBuilder authenticationManagerBuilder;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenProvider jwtTokenProvider;



    @GetMapping("/code")
    public ResEntity getCode(String phone) throws IOException, HTTPException {
        Sms sms = new Sms();
        sms.setPhone(phone);
        //生成验证码
        String code = smsService.generateAuthCode(phone);

        sms.setCode(code);
        //手机号发送验证码
        SmsUtils.send(sms);
        return ResponseUtil.success("发送验证码成功");
    }



    @PostMapping("/register")
    public ResEntity register(User user, Sms sms){
        System.out.println(user);
        System.out.println(sms);
        //校验用户
        ValidatorUtil.isUsername(user.getUsername());
        ValidatorUtil.isPassword(user.getPassword());
        ValidatorUtil.isEmail(user.getMail());
        ValidatorUtil.isMobile(user.getPhone());
        //检查用户名是否重复
        if(userService.queryByUsername(user.getUsername())!=null){
            return ResponseUtil.error(400,"用户名已存在");
        }
        //校验手机号与验证码是否对应
        ResEntity responseEntity = smsService.verifyAuthCode(sms.getPhone(), sms.getCode());
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setState(1);
        user.setType(0);
        userService.insert(user);
        return ResponseUtil.success(user);
    }



    @PostMapping("/login")
    public ResEntity login(@RequestBody User user, HttpServletResponse httpServletResponse){
        System.out.println(user);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword() );
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        String token = jwtTokenProvider.createJwtToken(authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        httpServletResponse.setHeader("Authorization", "Bearer" + " " + token);
        map.put("username", user.getUsername());

        return ResponseUtil.success(map);
    }


}